-- ===========================
-- Combine all the data after it has been exported.
-- ===========================
dofile("formats.lua")

-- ===========================
-- Extract the .lua file in the directory
-- ===========================
local function GetOrunjSaveFile(directory)
	for line in io.popen("dir " .. directory):lines() do
		if debug then print(line) end
		local f = string.match(line, "%d%d%.%d%d%.%d%d@%d%d%-%d%d%-%d%d%.lua")
		if f then return f end
	end
	return nil
end

-- ===========================
-- Return the subdirectories created by OrunjExport.lua
-- ===========================
local function GetScannableDirectories()
	local directories = {}
	for line in io.popen("dir"):lines() do
		if debug then print(line) end
		local d = string.match(line, "%d%d%.%d%d%.%d%d@%d%d%-%d%d%-%d%d")
		table.insert(directories, d)
	end
	return directories
end

-- ===========================
-- Analyze the contents of the directory.
-- ===========================
local function ClassifyDirectory(directory, charMapBuckets)
	print("Classifying directory: " .. directory)

	-- Open the directory's .lua file
	local filename = GetOrunjSaveFile(directory)
	if not filename then 
		print("No Lua file found in " .. directory .. ".")
		return nil
	end
	
	-- load the file.
	dofile(directory .. "/" .. filename)
	if not OrunjSave then
		print("No session found in " .. directory .. "/" .. filename)
		return
	end
	
	-- Get the first session in the OrunjSave table.
	local session = nil
	for k, v in pairs(OrunjSave.sessions) do
		session = v
		break
	end
	if not session then return end
	
	-- Extract the character from the session.
	local characterName = nil
	for k, v in pairs(session.players) do
		if v.name == "Appuls" or v.name == "Aid" or
			v.name == "Broccoli" or	v.name == "Orunjs" then
			characterName = v.name
			break
		end
	end
	if not characterName then return end
	
	-- Get the unique maps visited
	local uniqueMaps = {}
	for k, map in pairs(session.globalTimelines.mapTimeline) do
		uniqueMaps[map] = true
	end
	
	-- For each unique map, add the corresponding data file to the character's visited maps bucket
	local sessionName = string.match(filename, "%d%d%.%d%d%.%d%d@%d%d%-%d%d%-%d%d")
	for mapName, v in pairs(uniqueMaps) do
		if not charMapBuckets[characterName][mapName] then
			charMapBuckets[characterName][mapName] = {}
		end 
		table.insert(charMapBuckets[characterName][mapName], 
						directory .. "/" .. sessionName .. filenameSuffixes.position .. mapName .. extensions.data)
	end
end

-- ===========================
-- For each character, make a gnuplot script to plot all the MEC's in each map he visited.
-- ===========================
local function CreateAggregatePositionGnuplotScript(charMapBuckets, format)
	-- For each character...
	for charName, visitedMaps in pairs(charMapBuckets) do
		os.execute("mkdir " .. charName)
		-- Go through the visited maps, and create a gnuplot script for each one.
		for mapName, dataFilenames in pairs(visitedMaps) do
			local gnuplotScriptFilename = charName .. "/" .. mapName .. extensions.gnuplot
			local file = io.open(gnuplotScriptFilename, "w")
			io.output(file)
			
			io.write("#Cumulative MEC data for " .. charName .. " on " .. mapName .. "\n")
			io.write("reset\n")
			if format then
				-- redirect output to the specified place
				io.write("set terminal " .. format.name .. "\n")
				io.write("set output \"" .. charName .. "/" .. mapName .. format.extension .. "\"\n")
			else
				-- defaults
				io.write("set terminal wxt\n") -- wxt is a nice window terminal.
				io.write("set output\n")
			end
			
			io.write("set title \"Cumulative MEC data for " .. charName .. " on " .. mapName .. " (" .. #dataFilenames .. " sessions)" .. "\"\n")
			io.write("set autoscale\n")
			io.write("set xrange [0:1]\n")
			io.write("set yrange [0:1]\n")
		
			io.write("plot ")
			local first = true
			for i, dataFilename in ipairs(dataFilenames) do
				if not first then io.write(" , ") end
				io.write("\"" .. dataFilename .. "\" ")
				io.write("using 2:3:4 notitle with circles lc rgb 'orange' fs transparent solid 0.02 noborder ")
				first = false
			end
			io.write("\n")
			io.write("set output\n")
			
			file:close()
			os.execute("gnuplot " .. gnuplotScriptFilename)
		end
	end
	
end 

-- ===========================
-- Analyze the exported data.
-- ===========================
local function Main()
	local directories = GetScannableDirectories()
	local charMapBuckets = {Aid = {}, Appuls = {}, Broccoli = {}, Orunjs = {}}
	for i,directory in ipairs(directories) do
		ClassifyDirectory(directory, charMapBuckets)
	end
	
	CreateAggregatePositionGnuplotScript(charMapBuckets, formats.pdf)
end

Main() 